<template>
	<div class="table-wrapper">
		<div class="top row justify-between">
			<div class="tip">(开启预警功能后至少填写一个接收人)</div>
			<el-button
				class="p-button"
				size="small"
				@click="addUser"
				:disabled="!isOpenWarning"
			>
				+ 添加
			</el-button>
		</div>
		<div class="table-box">
			<el-form
				ref="ruleFormRef"
				:model="ruleForm"
				:rules="rules"
				class="demo-ruleForm"
			>
				<el-table border :data="tableData" style="width: 100%">
					<el-table-column type="index" width="70" label="序号" align="center">
						<template #default="scope">
							<span>{{ pageSize * (pageIndex - 1) + scope.$index + 1 }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="userName" label="接收人姓名" width="180">
						<template #default="scope">
							<el-form-item
								:prop="`tableData.${scope.$index}.userName`"
								:rules="rules.userName"
								:show-message="false"
							>
								<el-input
									:disabled="!isOpenWarning"
									v-model="scope.row.userName"
									maxlength="10"
									placeholder="请输入接收人姓名"
								/>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column prop="phone" label="联系方式">
						<template #default="scope">
							<el-form-item
								:prop="`tableData.${scope.$index}.phone`"
								:rules="rules.phone"
							>
								<el-input
									:disabled="!isOpenWarning"
									v-model="scope.row.phone"
									maxlength="11"
									minlength="11"
									type="number"
									placeholder="请输入联系方式"
								/>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column fixed="right" label="操作" width="80" align="center">
						<template #default="scope">
							<el-button
								:disabled="!isOpenWarning"
								link
								type="primary"
								size="small"
								@click.prevent="deleteRow(scope.$index)"
							>
								移除
							</el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-form>
			<div class="page-line row justify-center">
				<el-pagination
					:page-size="pageSize"
					v-model:current-page="pageIndex"
					:hide-on-single-page="list.length < 9"
					layout="total, prev, pager, next"
					:total="list.length"
				/>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed, reactive } from "vue";
import { validatePhoneNumber } from "@/utils/common.ts";
import { ElMessage } from "element-plus";
import type { FormInstance } from "element-plus";

const emit = defineEmits(["delUser", "addUser"]);
const props = defineProps({
	list: {
		type: Array,
		required: true,
		default: () => [],
	},
	isOpenWarning: {
		type: Boolean,
		default: () => true,
	},
});

const pageSize = 8;
const pageIndex = ref(1);

// watch(pageIndex, (newValue, oldValue) => {
// 	checkForm((f) => {
// 		if (!f) {
// 			pageIndex.value = oldValue;
// 		}
// 	});
// });

const addUser = () => {
	pageIndex.value = Math.ceil(props.list.length / pageSize) || 1;
	emit("addUser");
};

const deleteRow = (index: number) => {
	emit("delUser", pageSize * (pageIndex.value - 1) + index);
};

const tableData = computed(() => {
	return props.list.slice(
		pageSize * (pageIndex.value - 1),
		pageSize * pageIndex.value,
	);
});

const ruleFormRef = ref<FormInstance>();
const ruleForm = computed(() => {
	return {
		tableData: tableData.value,
	};
});

const validatePhone = (rule: any, value: any, callback: any) => {
	if (!validatePhoneNumber(value)) {
		callback(new Error("请输入正确手机号！"));
	} else {
		callback();
	}
};

const rules = reactive({
	userName: [
		{ required: true, message: "接收人姓名不得为空", trigger: "blur" },
	],
	phone: [
		{ required: true, message: "手机号不能为空", trigger: "blur" },
		{
			validator: validatePhone,
			trigger: "blur",
			message: "请输入正确手机号！",
		},
	],
});

// 校验表单方法
const checkForm = async (callback) => {
	try {
		await ruleFormRef.value.validate();
		console.log("表单校验通过，数据：", tableData.value);
		callback(true);
		// 这里可以添加提交表单数据的逻辑
	} catch (error) {
		console.log("表单校验失败", error);
		ElMessage({
			message: "您输入的信息有误，请先检查！",
			type: "error",
		});
		callback(false);
	}
};

// 使用 defineExpose 暴露方法
defineExpose({
	checkForm,
});

onMounted(() => {
	// console.log("==========", ruleForm.value);
});
</script>

<style scoped lang="scss">
.table-wrapper {
	margin-top: 24px;
	.tip {
		color: rgb(217, 0, 27);
	}
	.table-box {
		margin-top: 12px;

		:deep(.el-table--fit) {
			.el-table__header-wrapper th {
				background-color: rgb(242, 242, 242);
				padding: 6px;
			}
			.el-table__body-wrapper td {
				padding: 4px;

				.cell {
					padding: 0;
				}
			}
		}
		.page-line {
			margin-top: 12px;
		}
	}
}
.el-form-item {
	margin-bottom: 0;
}
</style>
